//
//  ContactNode.m
//  AddressBookDemo
//
//  Created by wulanzhou on 2017/5/10.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

#import "ContactNode.h"
#import <MJExtension/MJExtension.h>
#import "NSString+PinYin.h"

@implementation ContactNode

MJCodingImplementation

- (instancetype)initContactNodeWithRecord:(ABRecordRef)onePerson{

    if (self = [super init]) {
        //获取recordID
        NSInteger contact_id = ABRecordGetRecordID(onePerson);
        self.contactID = [NSString stringWithFormat:@"%ld",(long)contact_id];
        
        //获取firstName
        self.firstName = (__bridge_transfer NSString*)ABRecordCopyValue(onePerson, kABPersonFirstNameProperty);
        
        //middleName
        self.middleName = (__bridge_transfer NSString *)ABRecordCopyValue(onePerson, kABPersonMiddleNameProperty);
        
        //lastName
        self.lastName = (__bridge_transfer NSString *)ABRecordCopyValue(onePerson, kABPersonLastNameProperty);
        
        // 读取firstname拼音音标
        self.firstPinyin = (__bridge_transfer NSString*)ABRecordCopyValue(onePerson, kABPersonFirstNamePhoneticProperty);
        
        //读取middleName拼音音标
        self.middlepinyin = (__bridge_transfer NSString *)ABRecordCopyValue(onePerson, kABPersonMiddleNamePhoneticProperty);
        
        // 读取lastname拼音音标
        self.lastPinyin = (__bridge_transfer NSString*)ABRecordCopyValue(onePerson, kABPersonLastNamePhoneticProperty);
        
        //nickName
        self.nickName = (__bridge_transfer NSString*)ABRecordCopyValue(onePerson, kABPersonNicknameProperty);
        
        //读取公司
        self.companyName = (__bridge_transfer NSString*)ABRecordCopyValue(onePerson, kABPersonOrganizationProperty);
        
        //birthDay
        self.birthday = (__bridge_transfer NSDate*)ABRecordCopyValue(onePerson, kABPersonBirthdayProperty);
        
        //获取头像
        if (ABPersonHasImageData(onePerson))
        {
            self.imageData = (__bridge_transfer NSData *)ABPersonCopyImageData(onePerson);
        }else{
            self.imageData = nil;
        }
        
        // 读取电话多值
        NSMutableArray *phonesList = [NSMutableArray arrayWithCapacity:0];
        ABMultiValueRef phone = ABRecordCopyValue(onePerson, kABPersonPhoneProperty);
        CFIndex phoneCount = ABMultiValueGetCount(phone);
        for (int i = 0; i < phoneCount; ++i) {
            //获取該Label下的电话值
            NSString *tempPhone = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, i);
            NSString *personPhone = [NSString stringWithString:tempPhone];
            //NSString *phoneNum = [self screenSpecialCharacterFromString:personPhone];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@"-" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@" " withString:@""];
            if (0 != [personPhone length]) {
                [phonesList addObject:personPhone];
            }
        }
        
        self.phoneList = phonesList;
        
    }
    
    return self;
}

- (instancetype)initContactNodeWithContact:(CNContact *)contact{

   if (self = [super init]) {
       
   
       self.contactID = contact.identifier;
       // 1.获取姓名
       self.firstName = contact.givenName; //名字
       self.middleName = contact.middleName;
       self.lastName = contact.familyName; //姓
       
       self.firstPinyin = contact.phoneticGivenName;
       self.middlepinyin = contact.phoneticMiddleName;
       self.lastPinyin = contact.phoneticFamilyName;
       
       //公司名称
       self.companyName = contact.organizationName;
       
       //昵称
       self.nickName = contact.nickname;
       
       //头像
       self.imageData = contact.imageData;
       
       //2.birthDay
       if(contact.birthday){
           NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
           NSDate *date = [gregorian dateFromComponents:contact.birthday];
           self.birthday   = date;
       }else{
           self.birthday = nil;
       }
       
       
       //手机号码
       NSMutableArray *phonesList = [NSMutableArray arrayWithCapacity:0];
       // 3.获取电话号码
       NSArray *phones = contact.phoneNumbers;
       if (phones && [phones count] > 0) {
           // 4.遍历电话号码
           for (CNLabeledValue *labelValue in phones) {
               CNPhoneNumber *phoneNumber = labelValue.value;
               [phonesList addObject:phoneNumber.stringValue];
               //NSLog(@"%@ %@", phoneNumber.stringValue, labelValue.label);
           }
       }
       self.phoneList = phonesList;
       
   }
   return self;
}

- (NSString *)getContactFullName
{
    //生成规则:无中文：(firstName MiddleName LastName) 中文：（LastName MiddleName FirstName)
    NSMutableString *nameStr = [NSMutableString stringWithFormat:@""];
    
    NSString *fName = @"";
    NSString *lName = @"";
    NSString *mName = @"";
    
    if (0 != [self.firstName length])
    {
        fName = self.firstName;
    }
    
    if (0 != [self.middleName length])
    {
        mName = self.middleName;
    }
    
    if (0 != [self.lastName length])
    {
        lName = self.lastName;
    }
    
    BOOL hasChinese = ([self containsChineseCharacter:self.firstName]
                       || [self containsChineseCharacter:self.firstPinyin]
                       || [self containsChineseCharacter:self.middleName]
                       || [self containsChineseCharacter:self.middlepinyin]
                       || [self containsChineseCharacter:self.lastName]
                       || [self containsChineseCharacter:self.lastPinyin]);
    
    //有中文字符 按lastName MiddleName firstName获取
    if (hasChinese)
    {
        [nameStr appendString:lName];
        if(0 != [nameStr length] && 0 != [mName length])
        {
            [nameStr appendString:@""];
        }
        [nameStr appendString:mName];
        if(0 != [nameStr length] && 0 != [fName length])
        {
            [nameStr appendString:@""];
        }
        [nameStr appendString:fName];
    }
    else
    {
        [nameStr appendString:fName];
        if(0 != [nameStr length] && 0 != [mName length])
        {
            [nameStr appendString:@""];
        }
        [nameStr appendString:mName];
        if(0 != [nameStr length] && 0 != [lName length])
        {
            [nameStr appendString:@""];
        }
        [nameStr appendString:lName];
    }
    
    //如果名字为空，公司名存在，就使用公司名
    if (0 == [nameStr length]) {
        if (self.companyName && [self.companyName length] > 0) {
            [nameStr appendString:self.companyName];
        }
    }
    
    //若名字为空，获取电话号码
    if (0 == [nameStr length])
    {
        if (self.phoneList && [self.phoneList count]>0)
        {
            return [self.phoneList objectAtIndex:0];
        }
        
        return @"";
    }
    
    return nameStr;
}


- (NSString *)getContactSortKey
{
    //获取联系人的全名称
    NSString *nameStr = [self getContactFullName];
    
    if (0 == [nameStr length])
    {
        return @"#";
    }
    else
    {
        //名字转化为首字母拼音
        NSString *pinYinName = [nameStr getFirstLetter];
        if (pinYinName && [pinYinName length] >0) {
            return pinYinName;
        }
    }
    
    return @"#";
}

#pragma mark -私有方法
- (BOOL)containsChineseCharacter:(NSString*)aStr
{
    for(int i = 0; i < [aStr length]; ++i)
    {
        unichar a = [aStr characterAtIndex:i];
        if(a >= 0x4e00 && a <= 0x9fff)
        {
            return YES;
        }
    }
    
    return NO;
}

@end
